import axios from 'axios';

function checkParams(params) {
  if (typeof params != 'object') return params
  for (let key in params) {
    const value = params[key];
    if (value === null || value === undefined || value === "") {
      delete params[key];
    }
  }
  return params;
}
//对象参数转为以？&拼接的字符
function paramsToStr(params) {
  let p = '';
  if (typeof params == 'object') {
    p = '?'
    for (let props in params) {
      p += `${props}=${params[props]}&`
    }
    p = p.slice(0, -1)
  }
  return p
}


const service = axios.create({
  // baseURL: 'https://im.svchain.xyz/api/', // 正式域名
  baseURL: 'http://192.168.2.44:8081/api/', // 测试域名
  timeout: 10000,
  header: {
    'content-type': 'application/json'
  },

});


// request拦截器
service.interceptors.request.use(
  config => {
    config.data = checkParams(config.data)
    config.params = checkParams(config.params)
    if (config.method == 'GET') {
      config.url += paramsToStr(config.params)
    }
    config.header.token = uni.getStorageSync('SVtoken');
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  async (response) => {
    // if (response.data) {
    // 	const {
    // 		code,
    // 		data,
    // 		msg
    // 	} = response.data;
    // }

    return Promise.resolve(response.data)
  },
  error => {
    return Promise.reject(error)
  }
)

export default service